package com.atmilan.quartz.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.atmilan.quartz.constant.Constants;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.mapper.StoreProductMapper;
import com.atmilan.quartz.mapper.StoreProductSourceMapper;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.BuyerProductSku;
import com.atmilan.quartz.model.entity.crmeb.StoreProduct;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttrResult;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttrValue;
import com.atmilan.quartz.model.entity.crmeb.StoreProductCate;
import com.atmilan.quartz.model.entity.crmeb.StoreProductCoupon;
import com.atmilan.quartz.model.entity.crmeb.StoreProductDescription;
import com.atmilan.quartz.model.entity.europe.EuropeProductSku;
import com.atmilan.quartz.service.IStoreProductAttrLuxuryService;
import com.atmilan.quartz.service.IStoreProductAttrResultLuxuryService;
import com.atmilan.quartz.service.IStoreProductAttrResultService;
import com.atmilan.quartz.service.IStoreProductAttrService;
import com.atmilan.quartz.service.IStoreProductAttrValueLuxuryService;
import com.atmilan.quartz.service.IStoreProductAttrValueService;
import com.atmilan.quartz.service.IStoreProductCateLuxuryService;
import com.atmilan.quartz.service.IStoreProductCateService;
import com.atmilan.quartz.service.IStoreProductCouponLuxuryService;
import com.atmilan.quartz.service.IStoreProductCouponService;
import com.atmilan.quartz.service.IStoreProductDescriptionLuxuryService;
import com.atmilan.quartz.service.IStoreProductDescriptionService;
import com.atmilan.quartz.service.IStoreProductLuxuryService;
import com.atmilan.quartz.service.IStoreProductSourceService;
import com.atmilan.quartz.service.ISystemAttachmentService;
import com.atmilan.quartz.sync.pull.buyer.service.IBuyerProductSkuService;
import com.atmilan.quartz.sync.pull.europe.service.IEuropeProductSkuService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
// TODO 未知错误, 行数227, 不会切换回数据库, 待排查
@DS("crmeb")
public class StoreProductSourceServiceImpl extends ServiceImpl<StoreProductSourceMapper, StoreProduct> implements IStoreProductSourceService {
    @Autowired
    private StoreProductMapper storeProductMapper;
    @Autowired
    private ISystemAttachmentService systemAttachmentService;
    @Autowired
    private IStoreProductAttrService storeProductAttrService;
    @Autowired
    private IStoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private IStoreProductAttrResultService storeProductAttrResultService;
    @Autowired
    private IStoreProductDescriptionService storeProductDescriptionService;
    @Autowired
    private IStoreProductCouponService storeProductCouponService;
    @Autowired
    private IStoreProductCateService storeProductCateService;
    /**** luxury相关处理 *****/
    @Autowired
    private IStoreProductLuxuryService storeProductLuxuryService;
    @Autowired
    private IStoreProductAttrLuxuryService storeProductAttrLuxuryService;
    @Autowired
    private IStoreProductAttrValueLuxuryService storeProductAttrValueLuxuryService;
    @Autowired
    private IStoreProductAttrResultLuxuryService storeProductAttrResultLuxuryService;
    @Autowired
    private IStoreProductDescriptionLuxuryService storeProductDescriptionLuxuryService;
    @Autowired
    private IStoreProductCouponLuxuryService storeProductCouponLuxuryService;
    @Autowired
    private IStoreProductCateLuxuryService storeProductCateLuxuryService;
    @Autowired
    private IBuyerProductSkuService buyerProductSkuService;
    @Autowired
    private IEuropeProductSkuService europeProductSkuService;
    
    /**
     * 售价费率
     * @Description:  
     * @author daigb 
     * @param @param product
     * @param @return
     * @return StoreProduct
     * @throws
     */
    private StoreProduct priceAdjustCrmeb(StoreProduct product) {
        // 欧洲商品只计算价格
        if(null != product.getIsEurope() && 1 == product.getIsEurope()) {
            product.setPrice(PriceUtil.calePrice(product.getPrice(), Constants.RATE_EUROPE_2_CRMEB));
            return product;
        }
        // 费率
        BigDecimal promotePrice = product.getPromotePrice();
        product.setPromotePrice(PriceUtil.calePrice(promotePrice, Constants.RATE_BUYER_2_CRMEB));

        // 没有活动价格
        product.setPrice(PriceUtil.calePrice(product.getPrice(), Constants.RATE_BUYER_2_CRMEB));
        product.setCost(PriceUtil.calePrice(product.getSourceCost(), Constants.RATE_BUYER_2_CRMEB_COST));

        return product;
    }
    private StoreProduct priceAdjustLuxury(StoreProduct product) {
        if(null != product.getIsEurope() && 1 == product.getIsEurope()) {
            product.setPrice(PriceUtil.calePrice(product.getPrice(), Constants.RATE_EUROPE_2_LUXURY));
            return product;
        }
        // 费率
        product.setPrice(PriceUtil.calePrice(product.getPrice(), Constants.RATE_BUYER_2_LUXURY));
        
        return product;
    }
    /*private void valuePriceAdjustCrmeb(StoreProductAttrValue value, StoreProduct product) {
        // 欧洲商品只计算价格
        if(null != product.getIsEurope() && 1 == product.getIsEurope()) {
            value.setPrice(PriceUtil.calePrice(value.getPrice(), RATE_LUXURY_2_CRMEB));
            return;
        }
        value.setPrice(PriceUtil.calePrice(value.getPrice(), RATE_CRMEB_2_CRMEB));
    }
    private void valuePriceAdjustLuxury(StoreProductAttrValue value, StoreProduct product) {
        if(null != product.getIsEurope() && 1 == product.getIsEurope()) {
            value.setPrice(PriceUtil.calePrice(value.getPrice(), RATE_LUXURY_2_LUXURY));
        } else {
            value.setPrice(PriceUtil.calePrice(value.getPrice(), RATE_LUXURY_2_CRMEB));
        }
    }*/

    /**
     * 新增产品
     * @param storeProductCrmebRequest 新增产品request对象
     * @return 新增结果
     */
    @Override
    public boolean save(StoreProductCrmebRequest storeProductCrmebRequest) {
        StoreProduct storeProduct = new StoreProduct();
        BeanUtils.copyProperties(storeProductCrmebRequest, storeProduct);
        storeProduct.setCreateTime(new Date());
        storeProduct.setImage(systemAttachmentService.clearPrefix(storeProduct.getImage()));
        storeProduct.setSliderImage(systemAttachmentService.clearPrefix(storeProduct.getSliderImage()));
        
        //计算价格
        calcPriceForAttrValues(storeProductCrmebRequest, storeProduct);
        // 不要显示成本价，显示最低sku售价
        double costPrice = storeProductCrmebRequest.getAttrValue().stream().mapToDouble(e -> e.getCost().doubleValue()).min().getAsDouble();
        //原成本价
        BigDecimal sourceCost = storeProductCrmebRequest.getSourceCost();
        double sellPrice = storeProductCrmebRequest.getAttrValue().stream().mapToDouble(e -> e.getPrice().doubleValue()).min().getAsDouble();
        // 原价
        double otPrice = storeProductCrmebRequest.getAttrValue().stream().mapToDouble(e -> e.getOtPrice().doubleValue()).min().getAsDouble();
        int stock = storeProductCrmebRequest.getAttrValue().stream().mapToInt(e -> e.getStock()).sum();
        // 过滤库存为0的数据
        if(0 >= stock) {
            log.info("--------------- 丢弃库存为0商品, 商品id: {} ---------------", storeProductCrmebRequest.getId());
            return false;
        }
        
        storeProduct.setCost(BigDecimal.valueOf(costPrice));
        storeProduct.setSourceCost(sourceCost);
        storeProduct.setPrice(BigDecimal.valueOf(sellPrice));
        storeProduct.setOtPrice(BigDecimal.valueOf(otPrice));
        storeProduct.setStock(stock);

        // 分别计算luxury商品和buy价格
        StoreProduct storeProductLuxury = new StoreProduct();
        BeanUtils.copyProperties(storeProduct, storeProductLuxury);
        storeProduct = priceAdjustCrmeb(storeProduct);
        storeProductLuxury = priceAdjustLuxury(storeProductLuxury);
        storeProductLuxury.setPostage(storeProduct.getPostage());

        //保存数据
        boolean save = this.save(storeProduct);
        storeProductLuxuryService.save(storeProductLuxury);
        if (null != storeProduct.getId()) {
            storeProductCrmebRequest.setId(storeProduct.getId());
        }
        if (storeProductCrmebRequest.getSpecType()) { // 多属性
            List<StoreProductAttr> attrs = storeProductCrmebRequest.getAttr();
            List<StoreProductAttr> attrsLuxury = attrs.stream().map(t -> {
                StoreProductAttr obj = new StoreProductAttr();
                BeanUtils.copyProperties(t, obj);
                return obj;
            }).collect(Collectors.toList());
            
            Integer id = storeProduct.getId();
            attrs.forEach(e -> {
                e.setProductId(id);
                e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
            });
            Integer idLuxury = storeProductLuxury.getId();
            attrsLuxury.forEach(e -> {
                e.setProductId(idLuxury);
                e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
            });
            boolean attrAddResult = storeProductAttrService.saveBatch(attrs);
            storeProductAttrLuxuryService.saveOrUpdateBatch(attrsLuxury);
            if (!attrAddResult) {
                log.warn("新增属性名失败");
            }
        } else { // 单属性
            StoreProductAttr singleAttr = new StoreProductAttr();
            singleAttr.setProductId(storeProduct.getId()).setAttrName("规格").setAttrValues("默认").setType(0);
            StoreProductAttr singleAttrLuxury = new StoreProductAttr();
            singleAttrLuxury.setProductId(storeProductLuxury.getId()).setAttrName("规格").setAttrValues("默认").setType(0);
            boolean attrAddResult = storeProductAttrService.save(singleAttr);
            storeProductAttrLuxuryService.save(singleAttrLuxury);
            if (!attrAddResult) {
                log.warn("新增属性名失败");
            }
            StoreProductAttrValue singleAttrValue = new StoreProductAttrValue();
            BigDecimal commissionL1 = BigDecimal.ZERO;
            BigDecimal commissionL2 = BigDecimal.ZERO;
            if (storeProductCrmebRequest.getAttrValue().size() > 0) {
                commissionL1 = null != storeProductCrmebRequest.getAttrValue().get(0).getBrokerage() ? storeProductCrmebRequest.getAttrValue().get(0).getBrokerage() : BigDecimal.ZERO;
                commissionL2 = null != storeProductCrmebRequest.getAttrValue().get(0).getBrokerageTwo() ? storeProductCrmebRequest.getAttrValue().get(0).getBrokerageTwo() : BigDecimal.ZERO;
            }

            singleAttrValue.setProductId(storeProduct.getId());
            singleAttrValue.setStock(storeProduct.getStock());
            singleAttrValue.setSuk("默认");
            singleAttrValue.setSales(storeProduct.getSales());
            singleAttrValue.setPrice(storeProduct.getPrice());
            singleAttrValue.setImage(systemAttachmentService.clearPrefix(storeProduct.getImage()));
            singleAttrValue.setCost(storeProduct.getCost()).setBarCode(storeProduct.getBarCode());
            singleAttrValue.setOtPrice(storeProduct.getOtPrice());
            singleAttrValue.setBrokerage(commissionL1);
            singleAttrValue.setBrokerageTwo(commissionL2);
            StoreProductAttrValue singleAttrValueLuxury = new StoreProductAttrValue();
            BeanUtils.copyProperties(singleAttrValue, singleAttrValueLuxury);
            singleAttrValueLuxury.setProductId(storeProductLuxury.getId());
            // 计算价格
            singleAttrValue.setPrice(storeProduct.getPrice());
            singleAttrValueLuxury.setPrice(storeProductLuxury.getPrice());
            if(null == storeProduct.getIsEurope() || 1 != storeProduct.getIsEurope()) {
                singleAttrValue.setCost(storeProduct.getCost());
            }

            // 查询sku信息
            if(ProductTypeEnum.EUROPE.getCode() == storeProduct.getIsEurope()) {
                EuropeProductSku europeProductSku = europeProductSkuService.getOne(Wrappers.<EuropeProductSku>lambdaQuery()
                        .eq(EuropeProductSku :: getGoodsId, storeProduct.getBarCode().substring(4))
                        .eq(EuropeProductSku :: getSuk, singleAttrValue.getSuk())
                        .last("LIMIT 1")
                        );
                singleAttrValue.setSourceSkuId(null == europeProductSku ? "" : europeProductSku.getId());
                singleAttrValueLuxury.setSourceSkuId(null == europeProductSku ? "" : europeProductSku.getId());
            } else if(ProductTypeEnum.BUYER.getCode() == storeProduct.getIsEurope()) {
                BuyerProductSku buyerProductSku = buyerProductSkuService.getOne(Wrappers.<BuyerProductSku>lambdaQuery()
                        .eq(BuyerProductSku :: getGoodsId, storeProduct.getBarCode().substring(4))
                        .eq(BuyerProductSku :: getSuk, singleAttrValue.getSuk())
                        .last("LIMIT 1")
                        );
                singleAttrValue.setSourceSkuId(null == buyerProductSku ? "" : buyerProductSku.getSkuId());
                singleAttrValueLuxury.setSourceSkuId(null == buyerProductSku ? "" : buyerProductSku.getSkuId());
            }
        
            boolean saveOrUpdateResult = storeProductAttrValueService.save(singleAttrValue);
            storeProductAttrValueLuxuryService.save(singleAttrValueLuxury);
            if (!saveOrUpdateResult) {
                log.warn("新增属性详情失败");
            }
        }
        if (null != storeProductCrmebRequest.getAttrValue() && storeProductCrmebRequest.getAttrValue().size() > 0) {
            // 批量设置attrValues对象的商品id
            List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = storeProductCrmebRequest.getAttrValue();
            List<StoreProductAttrValueRequest> storeProductAttrValuesRequestLuxury = new ArrayList<StoreProductAttrValueRequest>();

            List<StoreProductAttrValue> storeProductAttrValues = new ArrayList<>();
            List<StoreProductAttrValue> storeProductAttrValuesLuxury = new ArrayList<>();
            for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
                attrValuesRequest.setProductId(storeProduct.getId());
                StoreProductAttrValue spav = new StoreProductAttrValue();
                StoreProductAttrValue spavLuxury = new StoreProductAttrValue();
                BeanUtils.copyProperties(attrValuesRequest, spav);
                BeanUtils.copyProperties(attrValuesRequest, spavLuxury);
                spavLuxury.setProductId(storeProductLuxury.getId());
                //设置sku字段
                if (null == attrValuesRequest.getAttrValue()) {
                    break;
                }
                List<String> skuList = new ArrayList<>();
                for (Map.Entry<String, String> vo : attrValuesRequest.getAttrValue().entrySet()) {
                    skuList.add(vo.getValue());
                    spav.setSuk(String.join(",", skuList));
                    spavLuxury.setSuk(String.join(",", skuList));
                }

                // 查询sku信息
                if(ProductTypeEnum.EUROPE.getCode() == storeProduct.getIsEurope()) {
                    EuropeProductSku europeProductSku = europeProductSkuService.getOne(Wrappers.<EuropeProductSku>lambdaQuery()
                            .eq(EuropeProductSku :: getGoodsId, storeProduct.getBarCode().substring(4))
                            .eq(EuropeProductSku :: getSuk, spav.getSuk())
                            .last("LIMIT 1")
                            );
                    spav.setSourceSkuId(null == europeProductSku ? "" : europeProductSku.getId());
                    spavLuxury.setSourceSkuId(null == europeProductSku ? "" : europeProductSku.getId());
                } else if(ProductTypeEnum.BUYER.getCode() == storeProduct.getIsEurope()) {
                    BuyerProductSku buyerProductSku = buyerProductSkuService.getOne(Wrappers.<BuyerProductSku>lambdaQuery()
                            .eq(BuyerProductSku :: getGoodsId, storeProduct.getBarCode().substring(4))
                            .eq(BuyerProductSku :: getSuk, spav.getSuk())
                            .last("LIMIT 1")
                            );
                    spav.setSourceSkuId(null == buyerProductSku ? "" : buyerProductSku.getSkuId());
                    spavLuxury.setSourceSkuId(null == buyerProductSku ? "" : buyerProductSku.getSkuId());
                }
                
                spav.setImage(systemAttachmentService.clearPrefix(spav.getImage()));
                spavLuxury.setImage(spav.getImage());
                spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
                spavLuxury.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));

                // 意大利商品result
                StoreProductAttrValueRequest attrValuesRequestLuxury = new StoreProductAttrValueRequest();
                BeanUtils.copyProperties(attrValuesRequest, attrValuesRequestLuxury);
                // 计算价格
                spav.setPrice(storeProduct.getPrice());
                spavLuxury.setPrice(storeProductLuxury.getPrice());
                attrValuesRequest.setPrice(storeProduct.getPrice());
                attrValuesRequestLuxury.setPrice(storeProductLuxury.getPrice());
                attrValuesRequestLuxury.setCost(storeProductLuxury.getCost());
                if(null == storeProduct.getIsEurope() || 1 != storeProduct.getIsEurope()) {
                    spav.setCost(storeProduct.getCost());
                    attrValuesRequest.setCost(storeProduct.getCost());
                }
                storeProductAttrValuesRequestLuxury.add(attrValuesRequestLuxury);

                storeProductAttrValues.add(spav);
                storeProductAttrValuesLuxury.add(spavLuxury);
            }
            // 保存属性
            if (storeProductAttrValues.size() > 0) {
                boolean saveOrUpdateResult = storeProductAttrValueService.saveBatch(storeProductAttrValues);
                storeProductAttrValueLuxuryService.saveOrUpdateBatch(storeProductAttrValuesLuxury);
                
                StoreProductAttrResult attrResult = new StoreProductAttrResult(/*0, */storeProduct.getId(),
                        systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductCrmebRequest.getAttrValue())), 
                        Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)), Constants.PRODUCT_TYPE_NORMAL, storeProduct.getBarCode());
                StoreProductAttrResult attrResultLuxury = new StoreProductAttrResult(/*0,*/ storeProductLuxury.getId(),
                        systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductAttrValuesRequestLuxury)), 
                        Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)), Constants.PRODUCT_TYPE_NORMAL, storeProduct.getBarCode());
                storeProductAttrResultService.save(attrResult);
                storeProductAttrResultLuxuryService.save(attrResultLuxury);
                if (!saveOrUpdateResult) {
                    log.warn("新增属性详情失败");
                }
            }
        }

        // 处理富文本
        StoreProductDescription dbDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
        		.eq(StoreProductDescription :: getProductId, storeProduct.getId())
        		.last("LIMIT 1")
        		);
        StoreProductDescription storeProductDescription = StoreProductDescription.getDescriptionByProduct(storeProduct);
        storeProductDescription.setId(ObjectUtil.isNotNull(dbDescription) ? dbDescription.getId() : null);
        storeProductDescription.setProductId(storeProduct.getId());
        storeProductDescriptionService.saveOrUpdate(storeProductDescription);

        // 处理优惠券关联信息
        shipProductCoupons(storeProductCrmebRequest, storeProduct, storeProductLuxury);
        return save;
    }
    
    /**
     * 更新产品
     * @param storeProductCrmebRequest 更新产品request对象
     * @return 更新结果
     */
    @Override
    public boolean update(StoreProductCrmebRequest storeProductCrmebRequest) {
        StoreProduct storeProduct = new StoreProduct();
        BeanUtils.copyProperties(storeProductCrmebRequest, storeProduct);
        storeProduct.setCreateTime(new Date());

        //主图
        storeProduct.setImage(systemAttachmentService.clearPrefix(storeProduct.getImage()));

        //轮播图
        storeProduct.setSliderImage(systemAttachmentService.clearPrefix(storeProduct.getSliderImage()));

        calcPriceForAttrValues(storeProductCrmebRequest, storeProduct);

        // 分别计算luxury商品和buy价格
        StoreProduct storeProductLuxury = new StoreProduct();
        BeanUtils.copyProperties(storeProduct, storeProductLuxury);
        storeProduct = priceAdjustCrmeb(storeProduct);
        storeProductLuxury = priceAdjustLuxury(storeProductLuxury);

        boolean saveCount = this.updateById(storeProduct);
        storeProductLuxuryService.updateById(storeProductLuxury);

        // 对attr表做全量更新，删除原有数据保存现有数据
        storeProductAttrService.removeByProductId(storeProduct.getId());
        storeProductAttrLuxuryService.removeByProductId(storeProduct.getId());
        List<StoreProductAttrValue> attrValuelist = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getProductId, storeProduct.getId()));
        Map<String, StoreProductAttrValue> attrValueMap = attrValuelist == null ? MapUtil.newHashMap() : attrValuelist.stream().collect(Collectors.toMap(StoreProductAttrValue::getSuk, Function.identity()));
        if (CollectionUtils.isNotEmpty(storeProductCrmebRequest.getAttrValue())) {
            for (StoreProductAttrValueRequest attrValueRequest : storeProductCrmebRequest.getAttrValue()) {
                if (null != attrValueRequest.getAttrValue()) {
                    List<String> skuList = new ArrayList<>();
                    for (Map.Entry<String, String> vo : attrValueRequest.getAttrValue().entrySet()) {
                        skuList.add(vo.getValue());
                    }
                    attrValueRequest.setSuk(String.join(",", skuList));
//                    attrValueRequest.setId(attrValueMap.containsKey(attrValueRequest.getSuk()) ? attrValueMap.get(attrValueRequest.getSuk()).getId() : null);
                }

            }
        }

        if (storeProductCrmebRequest.getSpecType()) { //  确认单属性商品的attr参数
            storeProductCrmebRequest.getAttr().forEach(e -> {
                e.setProductId(storeProductCrmebRequest.getId());
                e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
            });
            List<StoreProductAttr> attrs = storeProductCrmebRequest.getAttr();
            storeProductAttrService.saveBatch(attrs);
            storeProductAttrLuxuryService.saveOrUpdateBatch(attrs);
            if (CollectionUtils.isNotEmpty(storeProductCrmebRequest.getAttrValue())) {

                List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = storeProductCrmebRequest.getAttrValue();
                List<StoreProductAttrValueRequest> storeProductAttrValuesRequestLuxury = new ArrayList<StoreProductAttrValueRequest>();

                // 批量设置attrValues对象的商品id
                List<StoreProductAttrValue> storeProductAttrValues = new ArrayList<>();
                List<StoreProductAttrValue> storeProductAttrValuesLuxury = new ArrayList<>();

                for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
                    attrValuesRequest.setProductId(storeProductCrmebRequest.getId());
                    
                    StoreProductAttrValue spav = new StoreProductAttrValue();
                    StoreProductAttrValue spavLuxury = new StoreProductAttrValue();
                    BeanUtils.copyProperties(attrValuesRequest, spav);
                    BeanUtils.copyProperties(attrValuesRequest, spavLuxury);
                    spavLuxury.setProductId(storeProductLuxury.getId());
                    
                    spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
                    spavLuxury.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));

                    // 意大利商品result
                    StoreProductAttrValueRequest attrValuesRequestLuxury = new StoreProductAttrValueRequest();
                    BeanUtils.copyProperties(attrValuesRequest, attrValuesRequestLuxury);
                    // 计算价格
                    spav.setPrice(storeProduct.getPrice());
                    spavLuxury.setPrice(storeProductLuxury.getPrice());
                    attrValuesRequest.setPrice(storeProduct.getPrice());
                    attrValuesRequestLuxury.setPrice(storeProductLuxury.getPrice());
                    attrValuesRequestLuxury.setCost(storeProductLuxury.getCost());
                    storeProductAttrValuesRequestLuxury.add(attrValuesRequestLuxury);
                    if(null == storeProduct.getIsEurope() || 1 != storeProduct.getIsEurope()) {
                        spav.setCost(storeProduct.getCost());
                        attrValuesRequest.setCost(storeProduct.getCost());
                    }

                    // 查询sku信息
                    if(ProductTypeEnum.EUROPE.getCode() == storeProduct.getIsEurope()) {
                        EuropeProductSku europeProductSku = europeProductSkuService.getOne(Wrappers.<EuropeProductSku>lambdaQuery()
                                .eq(EuropeProductSku :: getGoodsId, storeProduct.getBarCode().substring(4))
                                .eq(EuropeProductSku :: getSuk, spav.getSuk())
                                .last("LIMIT 1")
                                );
                        spav.setSourceSkuId(null == europeProductSku ? "" : europeProductSku.getId());
                        spavLuxury.setSourceSkuId(null == europeProductSku ? "" : europeProductSku.getId());
                    } else if(ProductTypeEnum.BUYER.getCode() == storeProduct.getIsEurope()) {
                        BuyerProductSku buyerProductSku = buyerProductSkuService.getOne(Wrappers.<BuyerProductSku>lambdaQuery()
                                .eq(BuyerProductSku :: getGoodsId, storeProduct.getBarCode().substring(4))
                                .eq(BuyerProductSku :: getSuk, spav.getSuk())
                                .last("LIMIT 1")
                                );
                        spav.setSourceSkuId(null == buyerProductSku ? "" : buyerProductSku.getSkuId());
                        spavLuxury.setSourceSkuId(null == buyerProductSku ? "" : buyerProductSku.getSkuId());
                    }

                    storeProductAttrValues.add(spav);
                    storeProductAttrValuesLuxury.add(spavLuxury);
                }
                storeProductAttrValueService.removeByProductId(storeProduct.getId());
                boolean saveOrUpdateResult = storeProductAttrValueService.saveBatch(storeProductAttrValues);
                storeProductAttrValueLuxuryService.saveOrUpdateBatch(storeProductAttrValuesLuxury);
                // attrResult整存整取，不做更新
                storeProductAttrResultService.remove(Wrappers.<StoreProductAttrResult>lambdaQuery().eq(StoreProductAttrResult::getProductId, storeProduct.getId()));
                storeProductAttrResultLuxuryService.remove(Wrappers.<StoreProductAttrResult>lambdaQuery().eq(StoreProductAttrResult::getProductId, storeProduct.getId()));

                StoreProductAttrResult attrResult = new StoreProductAttrResult(/*0,*/ storeProduct.getId(),
                        systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductCrmebRequest.getAttrValue())), 
                        Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)), Constants.PRODUCT_TYPE_NORMAL, storeProduct.getBarCode());
                StoreProductAttrResult attrResultLuxury = new StoreProductAttrResult(/*0,*/ storeProduct.getId(),
                        systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductAttrValuesRequestLuxury)), 
                        Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)), Constants.PRODUCT_TYPE_NORMAL, storeProduct.getBarCode());
                storeProductAttrResultService.save(attrResult);
                storeProductAttrResultLuxuryService.save(attrResultLuxury);
                if (!saveOrUpdateResult) {
                    log.warn("编辑属性详情失败");
                }

            }
        } else {
            StoreProductAttr singleAttr = new StoreProductAttr();
            singleAttr.setProductId(storeProduct.getId()).setAttrName("规格").setAttrValues("默认").setType(0);
            boolean attrAddResult = storeProductAttrService.save(singleAttr);
            storeProductAttrLuxuryService.save(singleAttr);
            if (!attrAddResult) {
                log.warn("新增属性名失败");
            }
            StoreProductAttrValue singleAttrValue = new StoreProductAttrValue();
            if (storeProductCrmebRequest.getAttrValue().size() == 0) {
                log.warn("attrValue不能为空");
            }
            StoreProductAttrValueRequest attrValueRequest = storeProductCrmebRequest.getAttrValue().get(0);
            BeanUtils.copyProperties(attrValueRequest, singleAttrValue);
            singleAttrValue.setProductId(storeProduct.getId());
            singleAttrValue.setSuk("默认");
            singleAttrValue.setImage(systemAttachmentService.clearPrefix(singleAttrValue.getImage()));
            
            StoreProductAttrValue singleAttrValueLuxury = new StoreProductAttrValue();
            BeanUtils.copyProperties(singleAttrValue, singleAttrValueLuxury);
            singleAttrValueLuxury.setProductId(storeProductLuxury.getId());

            // 计算价格
            singleAttrValue.setPrice(storeProduct.getPrice());
            singleAttrValueLuxury.setPrice(storeProductLuxury.getPrice());
            if(null == storeProduct.getIsEurope() || 1 != storeProduct.getIsEurope()) {
                singleAttrValue.setCost(storeProduct.getCost());
            }
            storeProductAttrValueService.removeByProductId(storeProduct.getId());
            boolean saveOrUpdateResult = storeProductAttrValueService.save(singleAttrValue);
            storeProductAttrValueLuxuryService.saveOrUpdate(singleAttrValueLuxury);
            if (!saveOrUpdateResult) {
                log.warn("新增属性详情失败");
            }
        }

        // 处理分类辅助表
        if (null != storeProductCrmebRequest.getCateIds()) {
            for (int i = 0; i < storeProductCrmebRequest.getCateIds().size(); i++) {
                Integer cateid = storeProductCrmebRequest.getCateIds().get(i);
                StoreProductCate storeProductCate = new StoreProductCate(storeProduct.getId(), cateid, Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
                LambdaUpdateWrapper<StoreProductCate> luw = new LambdaUpdateWrapper<>();
                luw.set(StoreProductCate::getProductId, storeProductCate.getProductId());
                luw.set(StoreProductCate::getCateId, storeProductCate.getCateId());
                luw.set(StoreProductCate::getAddTime, storeProductCate.getAddTime());
                storeProductCateService.update(luw);
                storeProductCateLuxuryService.update(luw);
            }
        }

        // 处理富文本
        StoreProductDescription dbDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
        		.eq(StoreProductDescription :: getProductId, storeProduct.getId())
        		.last("LIMIT 1")
        		);
        StoreProductDescription storeProductDescription = StoreProductDescription.getDescriptionByProduct(storeProduct);
        storeProductDescription.setId(ObjectUtil.isNotNull(dbDescription) ? dbDescription.getId() : null);
        storeProductDescription.setProductId(storeProduct.getId());
        storeProductDescriptionService.saveOrUpdate(storeProductDescription);

        //productSearchService.updateProductData(storeProduct.getId());
        // 处理优惠券关联信息
        shipProductCoupons(storeProductCrmebRequest, storeProduct, storeProductLuxury);
        return saveCount;
    }

    @Override
    public StoreProduct getByBarCode(String barCode) {
        return getOne(Wrappers.<StoreProduct>lambdaQuery().eq(StoreProduct::getBarCode, barCode).last("LIMIT 1"));
    }

    /**
     * 计算产品属性之中最大和最小的价格，新增和编辑使用
     * @param storeProductCrmebRequest 分析的参数
     * @param storeProduct 当前操作的产品
     */
    private void calcPriceForAttrValues(StoreProductCrmebRequest storeProductCrmebRequest, StoreProduct storeProduct) {
        // 不要显示成本价，显示最低sku售价
        double costPrice = storeProductCrmebRequest.getAttrValue().stream().mapToDouble(e -> e.getCost().doubleValue()).min().getAsDouble();

        //原成本价
        BigDecimal sourceCost = storeProductCrmebRequest.getSourceCost();

        double sellPrice = storeProductCrmebRequest.getAttrValue().stream().mapToDouble(e -> e.getPrice().doubleValue()).min().getAsDouble();
        // 原价
        double otPrice = storeProductCrmebRequest.getAttrValue().stream().mapToDouble(e -> e.getOtPrice().doubleValue()).min().getAsDouble();

        int stock = storeProductCrmebRequest.getAttrValue().stream().mapToInt(e -> e.getStock()).sum();
        storeProduct.setCost(BigDecimal.valueOf(costPrice));
        storeProduct.setSourceCost(sourceCost);
        storeProduct.setPrice(BigDecimal.valueOf(sellPrice));
        storeProduct.setOtPrice(BigDecimal.valueOf(otPrice));
        storeProduct.setStock(stock);
    }

    /**
     * 设置优惠券信息
     * @param storeProductRequest 商品request信息
     * @param storeProduct 商品信息
     */
    private void shipProductCoupons(StoreProductCrmebRequest storeProductCrmebRequest, StoreProduct storeProduct,  StoreProduct storeProductLuxury) {
        if (null != storeProductCrmebRequest.getCouponIds() && storeProductCrmebRequest.getCouponIds().size() > 0) {
            storeProductCouponService.deleteByProductId(storeProduct.getId());
            storeProductCouponLuxuryService.deleteByProductId(storeProductLuxury.getId());
            List<StoreProductCoupon> spcs = new ArrayList<>();
            List<StoreProductCoupon> spcsLuxury = new ArrayList<>();
            for (Integer couponId : storeProductCrmebRequest.getCouponIds()) {
                StoreProductCoupon spc = new StoreProductCoupon(storeProduct.getId(), couponId, Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
                StoreProductCoupon spcLuxury = new StoreProductCoupon(storeProductLuxury.getId(), couponId, Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
                spcs.add(spc);
                spcsLuxury.add(spcLuxury);
            }
            storeProductCouponService.saveCoupons(spcs);
            storeProductCouponLuxuryService.saveCoupons(spcsLuxury);
        }
    }

    @Override
    public void deleteAll() {
        storeProductMapper.deleteAll();
    }

}
